package com.managedBean.home;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.controller.merchant.OffersController;
import com.dto.merchant.OffersDTO;

@ManagedBean(name = "homeManagedBean")
@SessionScoped
public class HomeManagedBean implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3484901558133535622L;

	private List<OffersDTO> offersList;
	
	@ManagedProperty(value = "#{offersController}")
	private OffersController offersController ;

	@PostConstruct
	public void populateItems() {
		try {
			offersList = offersController.findAll();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public StreamedContent getItemImage() throws IOException {
		FacesContext facesContext = FacesContext.getCurrentInstance();

		if (facesContext.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			return new DefaultStreamedContent();
		} else {
			String id = facesContext.getExternalContext()
					.getRequestParameterMap().get("imageId");
			OffersDTO dto  = new OffersDTO();
			for (OffersDTO var : offersList) {
				if (String.valueOf(var.getIdoffersTable()).equalsIgnoreCase(id)) {
					dto = var;
					break;
				}
			}
			DefaultStreamedContent img = new DefaultStreamedContent();
			try {
				if (null != dto && null != dto.getOfferImage()) {
					ByteArrayInputStream bis = new ByteArrayInputStream(
							dto.getOfferImage());
					img = new DefaultStreamedContent(bis);
					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return img;

		}
	}

	
	/**
	 * @return the offersList
	 */
	public List<OffersDTO> getOffersList() {
		return offersList;
	}

	/**
	 * @param offersList the offersList to set
	 */
	public void setOffersList(List<OffersDTO> offersList) {
		this.offersList = offersList;
	}

	/**
	 * @return the offersController
	 */
	public OffersController getOffersController() {
		return offersController;
	}

	/**
	 * @param offersController the offersController to set
	 */
	public void setOffersController(OffersController offersController) {
		this.offersController = offersController;
	}

	

	
}
